//index.js
//获取应用实例
const app = getApp();
const api = require("../../utils/api.js");
const _http = require("../../utils/request.js");
const utils = require("../../utils/util.js");

const QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
let qqmapsdk = new QQMapWX({
    key: 'DHABZ-AJTCQ-URZ5X-GSHDR-6OMVJ-JXBUK' // 必填
})

let interval = null

Page({
    mapCtx: null,
    data: {
        isShowInfo: false,
        isQiXingZhong: false,
        isQidong: true,
        isBind: true,
        isAuthorization: false,
        isPhoneAuthorization: false,
        isGetUserProfile: false,
        markerId: '',
        qiXingInfo: {},
        stationInfo: {
            siteName: '',
            distance: 0,
            pillarStill: 0,
            pillarBorrow: 0,
            pillarBad: 0
        },
        siteName: '',
        longitude: '',
        latitude: '',
        points: [],
        markers: [],
        startPoint: {
            latitude: null,
            longitude: null
        },
        endPoint: {
            latitude: null,
            longitude: null
        },
        polyline: [
            // {
            //     points: [{
            //         latitude: 22.829632051072952,
            //         longitude: 108.33133154541015
            //     }, {
            //         longitude: 108.31553869873046,
            //         latitude: 22.827417038821515
            //     }],
            //     color: "#32B458",
            //     width: 2,
            //     dottedLine: false,
            //     arrowLine: true,
            //     // borderColor:"#000",
            //     // borderWidth:5
            // }
        ]
    },
    onShow: function (options) {
        if (wx.getStorageSync('authorization')) {
            this.getOpen();
        }
        if (wx.getStorageSync('siteName')) {
            this.setData({
                siteName: wx.getStorageSync('siteName')
            });
        } else {
            if (wx.getStorageSync('authorization')) {
                this.getLocation();
            }
        }
    },
    onHide: function () {
        this.setData({
            siteName: '',
            isShowInfo: false
        }, () => {
            wx.removeStorageSync('siteName')
        });
    },
    onLoad: function (options) {
        
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        this.mapCtx = wx.createMapContext('map')
        if (wx.getUserProfile) {
            this.setData({
                isGetUserProfile: true
            })
        } else {
            this.setData({
                isGetUserProfile: false
            })
        }
        // if (wx.getStorageSync('authorization')) {
        //     this.getOpen();
        // }
        setTimeout(() => {
            this.setData({
                isQidong: false,
                isAuthorization: !wx.getStorageSync('authorization'),
            }, () => {
                this.getLocation();
            })
        }, 3000)
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        // return {
        //     title: `${wx.getStorageSync('nickName') ? wx.getStorageSync('nickName') + ' 邀请你' : ''}一起来抢隐藏京东优惠啦，购物拿返利，分享赚佣金！`,
        //     path: `/pages/index/index${wx.getStorageSync('inviteCode') ? '?c=' + wx.getStorageSync('inviteCode') : ''}`,
        //     imageUrl: "https://cdn.cailu88.com/jingxuanshi/share_image@2x.jpg"
        // }
    },
    getLocation(type) {
        let _this = this;
        wx.getLocation({
            type: 'gcj02',
            altitude: true,
            isHighAccuracy: true,
            //定位成功，更新定位结果      
            success(res) {
                const { longitude, latitude } = res;
                wx.setStorageSync('location', {
                    longitude,
                    latitude,
                })
                _this.setData({
                    // longitude: '108.33133154541015',
                    // latitude: '22.829632051072952',
                    longitude,
                    latitude,
                    startPoint: {
                        longitude,
                        latitude
                        // longitude: '108.33133154541015',
                        // latitude: '22.829632051072952',
                    }
                }, () => {
                    if (type === 'daohang') {
                        _this.getDetail(true)
                    }
                    _this.getStation(_this.data.longitude, _this.data.latitude);
                    if (wx.getStorageSync('authorization')) {
                        _this.getOpen();
                    }
                });
                // _this.setData({
                //     longitude: '108.32480841308593',
                //     latitude: '22.82804990314293',
                // }, () => {
                //     _this.getStation(_this.data.longitude, _this.data.latitude);
                // })
            }, //定位失败回调      
            fail() {
              wx.hideLoading();
            },
            complete() {
              //隐藏定位中信息进度       
              wx.hideLoading()
            }
        })
    },
    getStation (lon, lat) {
        _http(api.stations, 'get', {
        //   lon: 22.800316,
        //   lat: 108.331897,
            lon,
            lat,
            siteName: this.data.siteName,
            page: 1,
            pageSize: 20
        }).then(res => {
            let arr = res.data.returnObject.list
            if (!arr.length) {
                wx.showToast({
                  title: '该区域无站点',
                  icon: 'none',
                  duration: 2000
                })
                return
            }
            let points = this.data.points
            points.push({
                longitude: arr[0].longitude,
                latitude: arr[0].latitude
            })
            arr.map((t, i) => {
                t.id = Number(t.siteNum)
                t.latitude = t.lat
                t.longitude = t.lon
                t.iconPath = `../../image/marker_${t.stateIcon}@2x.png`
                t.width = 31
                t.height = 33
                t.anchor = {x: 0.5, y: 1}
            })
            this.setData({
                markers: arr,
                points
            })
            if (this.data.siteName) {
                this.setData({
                    latitude: arr[0].latitude,
                    longitude: arr[0].longitude
                })
            }
        })
    },
    handleScan () {
        wx.scanCode({
            onlyFromCamera: true,
            success: (res) => {
                console.log(res)
                wx.showLoading({
                  title: '开锁中...',
                  duration: 9999999
                })
                _http(api.openLock, 'get', {
                    url: res.result
                }).then(res => {
                    console.log(res)
                    setTimeout(() => {
                        wx.hideLoading()
                        wx.showToast({
                          title: '开锁成功',
                          icon: 'success',
                          duration: 3000
                        })
                        this.setData({
                            isQiXingZhong: true
                        })
                        this.shutdownLock()
                    }, [5000])
                }).catch(() => {
                    wx.showToast({
                        title: '开锁失败',
                        duration: 3000
                      })
                })
            }
        })
    },
    shutdownLock () {
        _http(api.shutdownLock, 'get', {}).then(res => {
            console.log(res)
            if (res.data.returnObject.info.repayFlag === 1) {
                this.setData({
                    qiXingInfo: {
                        useAmount: res.data.returnObject.info.useAmount,
                        cyclingDistance: res.data.returnObject.info.cyclingDistance,
                        cyclingTime: res.data.returnObject.info.cyclingTime,
                    }
                })
                clearInterval(interval)
                interval = setInterval(() => {
                    this.shutdownLock()
                }, [30000])
            } else {
                clearInterval(interval)
            }
        })
    },
    handleEndQiXing () {
        wx.showLoading({
            title: '还车中...',
            duration: 9999999
        })
        setTimeout(() => {
              wx.hideLoading()
              wx.showToast({
                title: '还车成功',
                icon: 'success',
                duration: 3000
              })
              this.setData({
                  isQiXingZhong: false
              })
        }, [5000])
    },
    handleLocation() {
        this.mapCtx.moveToLocation()
    },
    handlePay() {
        wx.navigateTo({
          url: '../bind/index',
        })
    },
    handleCoupons() {
        wx.navigateTo({
          url: '../coupons/index',
        })
    },
    handleProblem() {
        wx.navigateTo({
          url: '../guide/index',
        })
    },
    handleBreakDown() {
        wx.navigateTo({
          url: '../breakDown/index',
        })
    },
    handleMap () {
        this.setData({
            isShowInfo: false,
            polyline: []
        })
    },
    bindregionchange(e) {
        if (e.detail.centerLocation) {
            const {longitude, latitude} = e.detail.centerLocation;
            if (longitude && latitude) {
                wx.removeStorageSync('siteName')
                this.setData({
                    siteName: ''
                }, () => {
                    this.getStation(longitude, latitude);
                })
            }
        }
    },
    bindmarkertap(e) {
        const { markerId } = e.detail
        console.log(markerId)
        this.setData({
            markerId
        }, () => {
            this.getLocation('daohang')
        })
    },
    getDetail (bool) {
        _http(api.stations, 'get', {
            lon: this.data.startPoint.longitude,
            lat: this.data.startPoint.latitude,
            // lat: '108.33133154541015',
            // lon: '22.829632051072952',
            siteNum: this.data.markerId,
            page: 1,
            pageSize: 10
        }).then(res => {
            if (!res.data.returnObject.list.length) {
                wx.showToast({
                  title: '暂未获取详情',
                  icon: 'none'
                })
                return
            }
            this.setData({
                isShowInfo: true,
                stationInfo: res.data.returnObject.list[0],
                endPoint: {
                    longitude: res.data.returnObject.list[0].lon,
                    latitude: res.data.returnObject.list[0].lat,
                }
            }, () => {
                if (bool) {
                    this.getWalk()
                }
            })
        })
    },
    getWalk () {
        let _this = this;
        //调用距离计算接口
        qqmapsdk.direction({
            mode: 'walking',//可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
            //from参数不填默认当前地址
            from:  {
                // longitude: '108.33133154541015',
                // latitude: '22.829632051072952',
                latitude: _this.data.startPoint.latitude,
                longitude: _this.data.startPoint.longitude
              },
            to: {
                // longitude: 108.32339232205914,
                // latitude: 22.829618469052438
                latitude: _this.data.endPoint.latitude,
                longitude: _this.data.endPoint.longitude
            }, 
            success: function (res) {
                console.log('res------',res)
                let ret = res;
                let coors = ret.result.routes[0].polyline, pl = [];
                //坐标解压（返回的点串坐标，通过前向差分进行压缩）
                var kr = 1000000;
                for (var i = 2; i < coors.length; i++) {
                    coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
                }
                //将解压后的坐标放入点串数组pl中
                for (var i = 0; i < coors.length; i += 2) {
                    pl.push({ latitude: coors[i], longitude: coors[i + 1] })
                }
                //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
                _this.setData({
                    latitude: _this.data.startPoint.latitude,
                    longitude: _this.data.startPoint.longitude,
                    polyline: [{
                        points: pl,
                        color: '#32B458',
                        width: 4
                    }]
                })
            },
            fail: function (error) {
                if (error.status !== 0) {
                    wx.showToast({
                        title: error.message,
                        icon: 'none'
                    })
                }
            }
        })
    },
    getUserProfile(e) {
        // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
        // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
        wx.getUserProfile({
          desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
          success: (e) => {
            this.setData({
                isAuthorization: false,
            })
            wx.setStorageSync('authorization', true);
            wx.login({
                success: (res) => {
                    console.log('-----', e.userInfo)
                    _http(api.login, 'POST', {
                        code: res.code,
                        avatarUrl: e.userInfo.avatarUrl || '',
                        nickName: e.userInfo.nickName || '',
                        country: e.userInfo.country || '',
                        province: e.userInfo.province || '',
                        city: e.userInfo.city || '',
                        language: e.userInfo.language || '',
                        gender: e.userInfo.gender === 1 ? '男' : '女'
                    }).then(response => {
                        this.setData({
                            isPhoneAuthorization: response.data.returnObject.info.appletPhone ? false : true
                        })
                        wx.setStorageSync('openId', response.data.returnObject.info.openId);
                        this.getOpen(response.data.returnObject.info.openId);
                    })
                },
                fail: (err) => {
                    console.log(err)
                }
            })
          }
        })
      },

    /**
     * 获取用户信息
     */
    getUserInfo (e) {
        console.log('-----', e)
        if (e.detail.errMsg === 'getUserInfo:fail auth deny') {
            return
        }
        this.setData({
            isAuthorization: false,
        })
        wx.setStorageSync('authorization', true);
        wx.login({
            success: (res) => {
                console.log('-----', e.detail.userInfo)
                _http(api.login, 'POST', {
                    code: res.code,
                    avatar: e.detail.userInfo.avatarUrl || '',
                    nickName: e.detail.userInfo.nickName || '',
                    province: e.detail.userInfo.province || '',
                    city: e.detail.userInfo.city || '',
                    gender: e.detail.userInfo.gender === 1 ? '男' : '女'
                }).then(response => {
                    wx.setStorageSync('openId', response.data.returnObject.info.openId);
                    this.getOpen(response.data.returnObject.info.openId);
                })
            },
            fail: (err) => {
                console.log(err)
            }
        })
    },
    getPhoneNumber (e) {
        _http(api.phoneAuth, 'get', {
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv,
        }).then((res) => {
            const userInfo = res.data.returnObject.info
            wx.setStorageSync('userInfo', userInfo)
            this.setData({
                isPhoneAuthorization: false
            })
        }).catch((err) => {
            wx.showToast({
                title: err.data.message,
            })
        })
    },
    getOpen () {
        _http(api.open, 'get', {
            wechatOpenId: wx.getStorageSync('openId')
        }).then(res => {
            if (res.data.returnObject.info) {
                this.setData({
                    isBind: true
                })
                const userInfo = res.data.returnObject.info
                wx.setStorageSync('userInfo', userInfo)
                wx.setStorageSync('bind', true);
                this.setData({
                    isPhoneAuthorization: userInfo.appletPhone ? false : true
                })
                this.getStation(this.data.longitude, this.data.latitude);
            } else {
                this.setData({
                    isBind: false
                })
            }
        }).catch(err => {
            this.setData({
                isBind: false
            })
            wx.setStorageSync('bind', false);
        })
    },
    handleNavigation (e) {
      wx.createMapContext('map').openMapApp({
        longitude: e.currentTarget.dataset.lon,
        latitude: e.currentTarget.dataset.lat,
        // longitude: 108.33133154541015,
        // latitude: 22.829632051072952,
        destination: e.currentTarget.dataset.name,
        success(res) {
          console.log(res)
        },
        fail(err) {
          console.log(err)
        },
        complete(complete) {
          console.log(complete)
        }
      })
    },
    handleCollect (e) {
        _http(api.collection, 'get', {
            siteNum: e.currentTarget.dataset.num,
            wechatOpenId: wx.getStorageSync('openId')
        }).then(res => {
            this.getDetail()
            wx.showToast({
              title: '收藏成功',
              icon: 'none'
            })
        })
    },
    handleCancleCollect (e) {
        _http(api.cancelCollection, 'get', {
            siteNum: e.currentTarget.dataset.num,
            wechatOpenId: wx.getStorageSync('openId')
        }).then(res => {
            this.getDetail()
            wx.showToast({
              title: '已取消收藏',
              icon: 'none'
            })
        })
    }
})